import { Provide, Inject } from '@midwayjs/core';
import { DetectionDao } from '../dao/detection.dao';

interface CreateHistoryParams {
  userId: string;
  originalImageUrl: string;
  resultImage: string;
  ratio: number;
  diagnosis: string;
  filename: string;
  fileSize: number;
}

@Provide()
export class DetectionService {
  @Inject()
  detectionDao: DetectionDao;

  // 关键功能：创建检测历史记录
  async createHistory(userId: string, imageUrl: string): Promise<{ id: number }> {
    const id = await this.detectionDao.create(userId, imageUrl);
    return { id };
  }

  // 新功能：创建详细的AI检测历史记录
  async createHistoryWithDetails(params: CreateHistoryParams): Promise<{ id: number; createdAt: Date }> {
    const result = await this.detectionDao.createWithDetails(params);
    return result;
  }

  // 关键功能：分页获取用户检测历史
  async listHistory(userId: string, page: number, pageSize: number): Promise<{ list: any[]; total: number }> {
    const { list, total } = await this.detectionDao.list(userId, page, pageSize);
    const mapped = list.map(item => ({
      id: item.id,
      imageUrl: item.imageUrl,
      detectedAt: item.detectedAt,
    }));
    return { list: mapped, total };
  }

  // 关键功能：删除指定ID的检测历史（只允许删除当前用户的记录）
  async deleteHistory(userId: string, id: number): Promise<{ success: boolean }> {
    const ok = await this.detectionDao.delete(userId, id);
    if (!ok) {
      throw new Error('记录不存在或无权限');
    }
    return { success: true };
  }
}